<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { userApi } from '@/api'

const route = useRoute()
const router = useRouter()

// 用户ID
const userId = ref(route.params.id)

// 表单数据
const formData = reactive({
  id: null,
  username: '',
  email: '',
  phone: '',
  role: 'user',
  status: 1
})

// 加载状态
const loading = ref(false)
const submitting = ref(false)

// 错误信息
const errorMsg = ref('')
const successMsg = ref('')

// 获取用户详情
async function fetchUserDetail() {
  if (!userId.value) {
    errorMsg.value = '用户ID不能为空'
    return
  }
  
  loading.value = true
  errorMsg.value = ''
  
  try {
    const res = await userApi.getUser(userId.value)
    console.log('获取用户详情成功：', res)
    
    if (res.data) {
      Object.assign(formData, res.data)
    } else {
      errorMsg.value = '获取用户信息失败'
    }
  } catch (error) {
    console.error('获取用户详情失败：', error)
    errorMsg.value = '获取用户信息失败: ' + (error.message || '未知错误')
  } finally {
    loading.value = false
  }
}

// 提交表单
async function submitForm() {
  // 表单验证
  if (!formData.username.trim()) {
    errorMsg.value = '用户名不能为空'
    return
  }
  
  if (formData.email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.email)) {
    errorMsg.value = '邮箱格式不正确'
    return
  }
  
  if (formData.phone && !/^1[3-9]\d{9}$/.test(formData.phone)) {
    errorMsg.value = '手机号格式不正确'
    return
  }
  
  submitting.value = true
  errorMsg.value = ''
  successMsg.value = ''
  
  try {
    const res = await userApi.updateUser(formData)
    console.log('更新用户成功：', res)
    
    successMsg.value = '用户信息更新成功'
    
    // 2秒后返回用户管理页面
    setTimeout(() => {
      router.push('/dashboard/user')
    }, 2000)
    
  } catch (error) {
    console.error('更新用户失败：', error)
    errorMsg.value = '更新用户失败: ' + (error.message || '未知错误')
  } finally {
    submitting.value = false
  }
}

// 取消编辑
function cancelEdit() {
  router.push('/dashboard/user')
}

// 组件挂载时获取用户详情
onMounted(() => {
  fetchUserDetail()
})
</script>

<template>
  <div class="user-edit">
    <div class="page-header">
      <h2>编辑用户</h2>
      <div class="header-actions">
        <button class="btn btn-secondary" @click="cancelEdit">返回</button>
      </div>
    </div>
    
    <!-- 错误提示 -->
    <div v-if="errorMsg" class="message error-message">
      {{ errorMsg }}
    </div>
    
    <!-- 成功提示 -->
    <div v-if="successMsg" class="message success-message">
      {{ successMsg }}
    </div>
    
    <!-- 加载中 -->
    <div v-if="loading" class="loading-spinner">
      <div class="spinner"></div>
      <p>加载中...</p>
    </div>
    
    <!-- 编辑表单 -->
    <div v-else class="edit-form">
      <form @submit.prevent="submitForm">
        <div class="form-group">
          <label for="username">用户名 *</label>
          <input 
            id="username"
            v-model="formData.username" 
            type="text" 
            class="form-control"
            placeholder="请输入用户名"
            required
          >
        </div>
        
        <div class="form-group">
          <label for="email">邮箱</label>
          <input 
            id="email"
            v-model="formData.email" 
            type="email" 
            class="form-control"
            placeholder="请输入邮箱"
          >
        </div>
        
        <div class="form-group">
          <label for="phone">手机号</label>
          <input 
            id="phone"
            v-model="formData.phone" 
            type="tel" 
            class="form-control"
            placeholder="请输入手机号"
          >
        </div>
        
        <div class="form-group">
          <label for="role">角色 *</label>
          <select id="role" v-model="formData.role" class="form-control" required>
            <option value="user">普通用户</option>
            <option value="admin">管理员</option>
          </select>
        </div>
        
        <div class="form-group">
          <label for="status">状态 *</label>
          <select id="status" v-model="formData.status" class="form-control" required>
            <option :value="1">正常</option>
            <option :value="0">禁用</option>
          </select>
        </div>
        
        <div class="form-actions">
          <button 
            type="button" 
            class="btn btn-secondary" 
            @click="cancelEdit"
            :disabled="submitting"
          >
            取消
          </button>
          <button 
            type="submit" 
            class="btn btn-primary" 
            :disabled="submitting"
          >
            <span v-if="submitting">保存中...</span>
            <span v-else>保存</span>
          </button>
        </div>
      </form>
    </div>
  </div>
</template>

<style scoped>
.user-edit {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  padding: 20px;
  max-width: 600px;
  margin: 0 auto;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

h2 {
  margin: 0;
  color: #333;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.message {
  padding: 12px 16px;
  border-radius: 4px;
  margin-bottom: 20px;
  font-size: 14px;
}

.error-message {
  background-color: #ffebee;
  color: #d32f2f;
  border: 1px solid #ffcdd2;
}

.success-message {
  background-color: #e8f5e9;
  color: #2e7d32;
  border: 1px solid #c8e6c9;
}

.loading-spinner {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 0;
}

.spinner {
  width: 40px;
  height: 40px;
  border: 4px solid rgba(0, 0, 0, 0.1);
  border-radius: 50%;
  border-top-color: #4CAF50;
  animation: spin 1s ease-in-out infinite;
  margin-bottom: 10px;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

.edit-form {
  max-width: 500px;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
  font-weight: 600;
  color: #333;
}

.form-control {
  width: 100%;
  padding: 10px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
  transition: border-color 0.3s;
}

.form-control:focus {
  outline: none;
  border-color: #4CAF50;
  box-shadow: 0 0 0 2px rgba(76, 175, 80, 0.2);
}

.form-actions {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #eee;
}

.btn {
  padding: 10px 20px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.3s;
  min-width: 80px;
}

.btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.btn-primary {
  background-color: #4CAF50;
  color: white;
}

.btn-primary:hover:not(:disabled) {
  background-color: #43a047;
}

.btn-secondary {
  background-color: #f5f5f5;
  color: #666;
  border: 1px solid #ddd;
}

.btn-secondary:hover:not(:disabled) {
  background-color: #e9e9e9;
}
</style>